package com.project.blog.controller;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.blog.common.Result;
import com.project.blog.dto.UserQuery;
import com.project.blog.entity.User;
import com.project.blog.enums.RoleType;
import com.project.blog.exception.CustomException;
import com.project.blog.utils.JwtUtils;
import com.project.blog.utils.Utils;
import io.swagger.annotations.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author 代码奔腾
 * @since 2022-08-30
 */
@Api(tags="用户模块")
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @ApiResponses({
            @ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 400, message = "请求参数没填好"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    @ApiOperation(value = "查询所有用户", notes="查询所有用户的接口")
    @GetMapping("/")
    public List<User> list() {
        return userService.list();
    }



    @ApiOperation(value = "查询用户（带分页）", notes="查询用户（带分页）")
    @PostMapping("/page")
    public Result<?> findPage(@RequestBody UserQuery userQuery) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(User::getId);
        if (!StringUtils.isBlank(userQuery.getUsername())) {
            wrapper.like(User::getUsername, userQuery.getUsername());
        }
        Page<User> page = userService.page(new Page<>(
                        userQuery.getPageNum(),
                        userQuery.getPageSize()),
                wrapper
        );
        return Result.success(page);
    }
    @ApiOperation(value = "修改用户", notes="修改用户")
    @PostMapping("/save")
    public Object save(@Validated @RequestBody User user) {

        Integer userId = JwtUtils.getCurrentUserInfo();
        if (userId != null) {

            //普通用户
            if (RoleType.ROLE_USER.equals(user.getRoleType())) {
                if (!user.getId().equals(userId)) {
                    throw new CustomException("用户ID不相等，请重新登录后尝试");
                }
            }
            User userInfo = userService.getById(userId);

            if(userInfo != null) {
                //超级管理员
                if (RoleType.ROLE_ADMIN.equals(user.getRoleType()) && user.getRoleType().equals(userInfo.getRoleType())) {
                    userService.saveOrUpdate(user);
                }else{
                    throw new CustomException("用户权限与数据库不一致");
                }
            }else {
                throw new CustomException("用户未找到");
            }

            return Result.success();
        }
        return Result.error();
    }



    @ApiImplicitParams({
            //参数效验
            @ApiImplicitParam(name="ids",value="用户唯一id",required=true,paramType=""),
    })
    @ApiOperation(value = "删除用户", notes="删除用户")
    @PostMapping("/delBatch")
    public Object deleteBatch(@RequestBody List<Integer> ids) {
//        throw new CustomException(500, "删除错误");
        userService.removeByIds(ids);
        return Result.success();
    }

    @ApiImplicitParams({
            //参数效验
            @ApiImplicitParam(name="username",value="用户名",required=true,paramType=""),
            @ApiImplicitParam(name="password",value="密码",required=true,paramType=""),

    })
    @ApiOperation(value = "用户登录", notes="用户登录")
    @GetMapping("/login")
    public Result<?> login(@RequestParam("username") String username, @RequestParam("password") String password) {

//        md5(password+salt) = 数据库存的password值
        //通过用户名查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username)
                .last("limit 1");
        User userInfo = userService.getOne(wrapper);
        HashMap<Object, Object> returnInfo = new HashMap<>();
        if (userInfo != null) {
            if (userInfo.getPassword() != null) {
                if (userInfo.getPassword().equals(SecureUtil.md5(password + userInfo.getSalt()))) {
                    String token = JwtUtils.generateToken(userInfo);
                    HashMap<Object, Object> map = new HashMap<>();
                    map.put("id", userInfo.getId());
                    map.put("username", userInfo.getUsername());
                    map.put("email", userInfo.getEmail());
                    map.put("roleType", userInfo.getRoleType());
                    map.put("token", token);
                    returnInfo.put("userInfo", map);
                    returnInfo.put("menuList", "");
                    return Result.success(map);
                }

            }

        }
        return Result.error("请检查用户名密码是否正确");
    }



    @ApiOperation(value = "注册登录", notes="注册登录")
    @PostMapping("/register")
    public Object register(@Validated @RequestBody User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        int count = userService.count(wrapper);
        if (count >= 1) {
            throw new CustomException("用户名重复");
        }

        String password = user.getPassword();
        String salt = Utils.salt();
        String resultPassword = SecureUtil.md5(password + salt);
        user.setPassword(resultPassword);
        user.setSalt(salt);
        user.setRoleType(RoleType.ROLE_USER);
        userService.saveOrUpdate(user);
        return Result.success();
    }

}
